#include <future>
#include <iostream>
// #include <promise>
#include <gtest/gtest.h>

#include "log/logger.h"
#include "sync/os_semaphore.h"
#include "thread/os_thread.h"
// 测试os_thread的基本构造和析构功能
TEST(OsThreadTest, ConstructorAndDestructor)
{
    // 验证os_thread对象可以正常构造和析构
    os_thread thread;
    EXPECT_EQ(thread.getState(), os_thread::STATE_UNINITIALIZED);
    thread.pause();
    EXPECT_EQ(thread.getState(), os_thread::STATE_PAUSED);
}

// 测试os_thread的create接口功能
//(1) 创建线程，线程自动运行
//(2) 创建线程，挂起，恢复
TEST(OsThreadTest, CreateThread)
{
    os_thread thread;

    // 测试创建短时间任务线程,默认自动启动线程
    int value = 0;
    bool result = thread.create(
        [&value]() {
            os_thread::sleep_ms(10);
            value++;
        },
        os_thread::FUNCTION_SHORT_TASK, 0);

    EXPECT_TRUE(result);
    EXPECT_EQ(thread.getState(), os_thread::STATE_INITIALIZED);
    EXPECT_FALSE(thread.is_running());
    thread.set_thread_name("CreateThread1");
    thread.start();
    thread.join();
    EXPECT_FALSE(thread.is_running());
    EXPECT_EQ(value, 1);
    LOGI("test...1");
    os_thread thread2;
    // 测试创建短时间任务线程,启动之前被设置为挂起
    os_semaphore sem(0);

    bool ret = thread2.create(
        [&sem]() {
            os_thread::sleep_ms(10);
            sem.signal();
        },
        os_thread::FUNCTION_SHORT_TASK, 0);
    EXPECT_TRUE(ret);
    thread2.set_thread_name("CreateThread2");
    thread2.pause();
    thread2.start();
    LOGI("test...2");
    EXPECT_EQ(thread2.getState(), os_thread::STATE_PAUSED);
    if (!sem.try_wait_for(std::chrono::milliseconds(1000))) {
        EXPECT_TRUE(true);
    } else {  // 线程执行成功,则不通过
        EXPECT_TRUE(false);
    }
    thread2.resume();
    LOGI("test...3");
    if (!sem.try_wait_for(std::chrono::milliseconds(1000))) {
        EXPECT_TRUE(false);
    }
    LOGI("test...4");
    thread2.join();
    LOGI("test...5");
    EXPECT_FALSE(thread2.is_running());
}
TEST(OsThreadTest, GetThreadId)
{
    os_thread thread;

    // 未启动线程时获取ID
    std::thread::id uninitialized_id = thread.get_threadid();

    thread.create(
        []() {
            os_thread::sleep_ms(1000);
        },
        os_thread::FUNCTION_SHORT_TASK, 0);

    thread.start();
    os_thread::sleep_ms(200);
    // 启动后获取ID
    std::thread::id running_id = thread.get_threadid();

    thread.join();

    // 结束后获取ID
    std::thread::id finished_id = thread.get_threadid();

    // 验证ID在不同状态下的一致性
    EXPECT_EQ(uninitialized_id, finished_id);
    EXPECT_NE(uninitialized_id, running_id);
}

// 测试os_thread的set_priority接口功能
TEST(OsThreadTest, SetPriority)
{
    os_thread thread;
    bool ret = thread.create(
        []() {
            os_thread::sleep_ms(10);
        },
        os_thread::FUNCTION_SHORT_TASK, 0);
    // 测试设置不同优先级
    EXPECT_TRUE(thread.set_priority(os_thread::PRIORITY_LOWEST));
    EXPECT_TRUE(thread.set_priority(os_thread::PRIORITY_LOW));
    EXPECT_TRUE(thread.set_priority(os_thread::PRIORITY_NORMAL));
    EXPECT_TRUE(thread.set_priority(os_thread::PRIORITY_HIGH));
    EXPECT_TRUE(thread.set_priority(os_thread::PRIORITY_HIGHEST));
    thread.set_thread_name("SetPriority");
    thread.start();
    thread.join();
}

// 测试os_thread的start接口功能
TEST(OsThreadTest, StartThread)
{
    os_thread thread;

    // 创建一个简单的线程函数
    bool executed = false;
    thread.create(
        [&executed]() {
            executed = true;
        },
        os_thread::FUNCTION_SHORT_TASK, 0);

    // 启动线程
    thread.set_thread_name("StartThread");
    EXPECT_TRUE(thread.start());
    thread.join();
    EXPECT_TRUE(executed);
}

// 测试os_thread的join接口功能
TEST(OsThreadTest, JoinThread)
{
    os_thread thread;

    std::atomic<bool> executed(false);
    auto fun = [&executed]() {
        os_thread::sleep_ms(50);
        executed.store(true);
        return;
    };

    thread.create(fun, os_thread::FUNCTION_SHORT_TASK, 0);
    thread.set_thread_name("JoinThread");
    thread.start();
    // 等待线程结束
    EXPECT_TRUE(thread.join());
    EXPECT_TRUE(executed.load());
}

// 测试os_thread的detach接口功能
// TEST(OsThreadTest, DetachThread)
// {
//     os_thread thread;
//     os_semaphore sem(0);
//     thread.create(
//         [&sem]() {
//             os_thread::sleep_ms(1000);
//             sem.signal();
//         },
//         os_thread::FUNCTION_SHORT_TASK, 0);
//     thread.set_thread_name("DetachThread");
//     thread.start();
//     // 分离线程
//     bool ret = thread.detach();
//     EXPECT_TRUE(ret);
//     LOGI("wait thread");
//     sem.wait();
//     LOGI("wait thread end");
// }
// 测试os_thread的set_attributes接口功能
TEST(OsThreadTest, SetAttributes)
{
    os_thread thread;

    // 测试设置线程属性接口
    EXPECT_TRUE(thread.set_attributes());
}

// 测试os_thread的pause和resume接口功能
TEST(OsThreadTest, PauseAndResume)
{
    os_thread thread;

    std::atomic<int> counter(0);
    thread.create(
        [&counter]() {
            counter++;
            LOGI("run");
            os_thread::sleep_ms(5);
        },
        os_thread::FUNCTION_SHORT_TASK, 5);
    thread.set_thread_name("PauseAndResume");
    thread.start();
    os_thread::sleep_ms(20);

    int count_before_pause = counter.load();

    // 暂停线程
    LOGI("call pase");
    thread.pause();
    os_thread::sleep_ms(30);

    int count_after_pause = counter.load();

    // 恢复线程
    LOGI("call resume");
    thread.resume();
    os_thread::sleep_ms(20);

    int count_after_resume = counter.load();

    // 验证暂停期间计数器没有增加
    EXPECT_EQ(count_before_pause, count_after_pause);
    // 验证恢复后计数器继续增加
    EXPECT_GT(count_after_resume, count_after_pause);
    LOGI("call terminate");
    thread.terminate();
    LOGI("call join");
    thread.join();
}

// 测试os_thread的terminate接口功能
TEST(OsThreadTest, TerminateThread)
{
    os_thread thread;
    LOGI("call create");
    thread.create(
        [&thread]() {
            while (true) {
                LOGI("etstst");
                if (thread.check_and_heart() == os_thread::STATE_CHECK_TERMINATED) {
                    break;
                }
                LOGI("etstst end");
                os_thread::sleep_ms(10);
            }
        },
        os_thread::FUNCTION_LONG_TASK, 0);
    thread.set_thread_name("TerminateThread");
    thread.start();

    // 终止线程
    LOGI("call terminate");
    thread.terminate();
    LOGI("call join");
    thread.join();

    EXPECT_TRUE(thread.is_finished());
}
// 测试os_thread的状态查询接口功能
TEST(OsThreadTest, StateQuery)
{
    os_thread thread;

    // 检查初始状态
    EXPECT_EQ(thread.getState(), os_thread::STATE_UNINITIALIZED);
    EXPECT_FALSE(thread.is_running());
    EXPECT_FALSE(thread.is_finished());

    // 创建线程后检查状态
    thread.create(
        []() {
            os_thread::sleep_ms(500);
        },
        os_thread::FUNCTION_SHORT_TASK, 0);

    EXPECT_EQ(thread.getState(), os_thread::STATE_INITIALIZED);
    EXPECT_FALSE(thread.is_running());
    EXPECT_FALSE(thread.is_finished());

    // 启动线程后检查状态
    thread.start();
    thread.wait_for_started();
    os_thread::sleep_ms(100);
    EXPECT_TRUE(thread.is_running());
    EXPECT_FALSE(thread.is_finished());

    // 线程结束后检查状态
    thread.join();
    EXPECT_FALSE(thread.is_running());
    EXPECT_TRUE(thread.is_finished());
}

// 测试os_thread的check_and_heart接口功能
TEST(OsThreadTest, CheckAndHeart)
{
    os_thread thread;

    bool should_continue = true;
    thread.create(
        [&should_continue, &thread]() {
            while (should_continue) {
                os_thread::sleep_ms(10);
                // 检查并更新心跳
                if (thread.check_and_heart() == os_thread::STATE_CHECK_TERMINATED) {
                    break;
                }
            }
        },
        os_thread::FUNCTION_LONG_TASK, 0);

    thread.start();
    os_thread::sleep_ms(20);

    // 检查心跳状态
    os_thread::check_state_e state = thread.check_and_heart();
    EXPECT_EQ(state, os_thread::STATE_CHECK_OK);

    thread.terminate();
    thread.join();
}

// 测试os_thread的set_thread_name和get_thread_name接口功能
TEST(OsThreadTest, ThreadName)
{
    os_thread thread;

    // 验证名称在创建线程后仍然保持
    thread.create(
        []() {
            os_thread::sleep_ms(50);
        },
        os_thread::FUNCTION_SHORT_TASK, 0);

    // 设置线程名称
    std::string name = "TestThread";
    thread.set_thread_name(name);

    // 获取线程名称
    EXPECT_EQ(thread.get_thread_name(), name);
}

// 测试os_thread的sleep相关接口功能
TEST(OsThreadTest, SleepFunctions)
{
    auto start = std::chrono::steady_clock::now();

    // 测试毫秒级休眠
    os_thread::sleep_ms(50);
    auto after_ms = std::chrono::steady_clock::now();
    auto ms_duration = std::chrono::duration_cast<std::chrono::milliseconds>(after_ms - start);
    EXPECT_GE(ms_duration.count(), 45);  // 允许一些误差

    // 测试微秒级休眠
    os_thread::sleep_us(10000);  // 10ms
    auto after_us = std::chrono::steady_clock::now();
    auto us_duration = std::chrono::duration_cast<std::chrono::milliseconds>(after_us - after_ms);
    EXPECT_GE(us_duration.count(), 5);  // 允许一些误差

    // 测试秒级休眠
    os_thread::sleep_second(0);  // 0秒休眠
    auto after_sec = std::chrono::steady_clock::now();
    auto sec_duration = std::chrono::duration_cast<std::chrono::milliseconds>(after_sec - after_us);
    EXPECT_LT(sec_duration.count(), 10);  // 应该几乎不耗时
}

// 测试os_thread的短时间任务周期性执行功能
TEST(OsThreadTest, ShortTaskPeriodicExecution)
{
    os_thread thread;

    std::atomic<int> execution_count(0);

    // 创建一个短时间任务，每10ms执行一次
    thread.create(
        [&execution_count]() {
            execution_count++;
        },
        os_thread::FUNCTION_SHORT_TASK, 10);
    thread.start();
    thread.wait_for_started();
    os_thread::sleep_ms(100);  // 等待大约5次执行
    thread.terminate();
    thread.join();

    // 验证任务被执行了大约5次 (55ms / 10ms = 5.5次)
    EXPECT_GE(execution_count.load(), 10 - 3);
    EXPECT_LE(execution_count.load(), 10 + 3);
}

// 测试os_thread的长时间任务执行功能
TEST(OsThreadTest, LongTaskExecution)
{
    os_thread thread;

    std::atomic<bool> task_running(false);
    std::atomic<bool> task_finished(false);

    thread.create(
        [&task_running, &task_finished, &thread]() {
            task_running = true;
            for (int i = 0; i < 10; i++) {
                if (thread.check_and_heart() == os_thread::STATE_CHECK_TERMINATED) {
                    break;
                }
                os_thread::sleep_ms(10);
            }
            task_running = false;
            task_finished = true;
        },
        os_thread::FUNCTION_LONG_TASK, 0);

    thread.start();
    os_thread::sleep_ms(30);

    // 验证任务正在运行
    EXPECT_TRUE(task_running.load());
    EXPECT_FALSE(task_finished.load());

    thread.join();

    // 验证任务已完成
    EXPECT_FALSE(task_running.load());
    EXPECT_TRUE(task_finished.load());
}